package com.example.HelloSpace.ui;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.example.HelloSpace.MainActivity;
import com.example.HelloSpace.R;
import com.example.HelloSpace.models.MissionInfoModel;
import com.example.HelloSpace.ui.mission_details.MissionDetailsFragment;
import com.example.HelloSpace.utils.MyApp;
import com.example.HelloSpace.utils.ViewUtils;
import com.example.HelloSpace.viewmodels.MissionListViewModel;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.android.material.textview.MaterialTextView;

public class MissionInfoView extends FrameLayout {
    private String URL;
    private CardView cardView;
    private ShapeableImageView image;
    private View fadeOverlay;

    //任务信息
    private MissionInfoModel missionInfoModel;
    private MissionListViewModel missionListViewModel;
    private String imageUrl;
    private TextView institution;
    private TextView missionName;
    private TextView launchTime;
    private MaterialTextView statusText;
    private CardView statusCard;

    private boolean isAnimating = false; // 动画状态标志
    private boolean isExpanded = false;



    public MissionInfoView(@NonNull Context context) {
        super(context);
        init(context);
    }

    public MissionInfoView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MissionInfoView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.view_mission_info, this, true);

        post(()->{
            if (getContext() instanceof Activity && !((Activity) getContext()).isFinishing()) {

                ViewUtils.resizeViewByWidth(context, this, 0.91f, 0.32f);
                // 设置渐变效果
                fadeOverlay.post(() -> applyFadeEffect(fadeOverlay, this,0.15f, 0.55f));

            }
        });
        URL= MyApp.getRESOURCE_URL();
        cardView = findViewById(R.id.card_view);
        institution = findViewById(R.id.company);
        missionName = findViewById(R.id.mission);
        launchTime = findViewById(R.id.launchDate);
        image = findViewById(R.id.imageView);
        fadeOverlay = findViewById(R.id.fadeOverlay);
        statusText = findViewById(R.id.state_tag_text);
        statusCard = findViewById(R.id.state_tag_card);
        cardView.setOnClickListener(v -> handleClick());
    }


    public void setMissionInfo(MissionInfoModel missionInfo) {
        this.missionInfoModel = missionInfo;
        imageUrl =missionInfo.getImageUrl();
        institution.setText(missionInfo.getInstitution());
        missionName.setText(missionInfo.getMissionName());
        launchTime.setText(missionInfo.getLaunchTime());
        setStatusTag(missionInfo);
        Glide.with(getContext())
                .load(URL+missionInfo.getImageUrl())
                .into(image);
    }

    public void setStatusTag(MissionInfoModel missionInfo){
        statusText.setText(missionInfo.getStatus());
        if(missionInfo.getStatus().equals("成功")){
            statusCard.setCardBackgroundColor(ContextCompat.getColor(getContext(), R.color.status_success));
        }
        else if(missionInfo.getStatus().equals("失败")){
            statusCard.setCardBackgroundColor(ContextCompat.getColor(getContext(), R.color.status_failure));
        }
        else if(missionInfo.getStatus().equals("异常")){
            statusCard.setCardBackgroundColor(ContextCompat.getColor(getContext(), R.color.status_anomaly));
        }
        else if(missionInfo.getStatus().equals("预计")){
            statusCard.setCardBackgroundColor(ContextCompat.getColor(getContext(), R.color.status_scheduled));
        }
        else{
            statusCard.setCardBackgroundColor(ContextCompat.getColor(getContext(), R.color.status_cancelled_or_custom));
        }
    }

    private void applyFadeEffect(View overlay, View view,float startRatio, float endRatio) {
        int width = overlay.getWidth();
        int height = view.getHeight();
        Log.d("applyFadeEffect", "width=" + width + ", height=" + height);

        if (width > 0 && height > 0) {
            // 定义渐变颜色
            int[] colors = new int[]{0x00FFFFFF, 0xFFFFFFFF};

            // 设置渐变起点和终点
            float angleInRadians = (float) Math.toRadians(-40); // 负值表示逆时针旋转
            float startX = startRatio * width;
            float startY = 0;
            float endX = endRatio * width;
            float endY = 0;

            // 计算旋转后的起点和终点
            float rotatedStartX = startX + height * (float) Math.sin(angleInRadians);
            float rotatedStartY = startY + height * (float) Math.cos(angleInRadians);
            float rotatedEndX = endX - height * (float) Math.sin(angleInRadians);
            float rotatedEndY = endY + height * (float) Math.cos(angleInRadians);

            // 创建一个带有旋转的线性渐变
            LinearGradient gradient = new LinearGradient(
                    rotatedStartX, rotatedStartY, rotatedEndX, rotatedEndY,
                    colors, null, Shader.TileMode.CLAMP
            );

            // 创建 Paint 并设置其 Shader
            Paint paint = new Paint();
            paint.setShader(gradient);
            // 将渐变应用到 View 的背景
            Bitmap bitmap = createBitmapWithShader(paint, width, height);
            Drawable drawable = new BitmapDrawable(overlay.getResources(), bitmap);
            overlay.setBackground(drawable);
        }
    }

    private Bitmap createBitmapWithShader(Paint paint, int width, int height) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawRect(0, 0, width, height, paint);
        return bitmap;
    }

    // 处理点击事件
    private void handleClick() {
        if (!isAnimating) {
            isAnimating = true; // 开始动画
            // 缩小动画
            cardView.animate()
                    .scaleX(0.95f)
                    .scaleY(0.95f)
                    .setDuration(100)
                    .withEndAction(() -> {
                        // 放大动画
                        cardView.animate()
                                .scaleX(1f)
                                .scaleY(1f)
                                .setDuration(75)
                                .withEndAction(() -> {
                                    expandToMissionDetails(); // 打开新页面
                                    isAnimating = false; // 动画结束
                                })
                                .start();
                    })
                    .start();
        }
    }
    private void expandToMissionDetails() {
        //设置选中的任务
        missionListViewModel.setSelectedMission(missionInfoModel);
        // 启动 MissionDetailsFragment
        MissionDetailsFragment detailsFragment = new MissionDetailsFragment();

        // 创建一个新的 Bundle 来传递参数（如果需要）
        Bundle fragmentArgs = new Bundle();
        // 需要传递的参数
        fragmentArgs.putInt("missionID",missionInfoModel.getId());
        fragmentArgs.putString("missionName",missionInfoModel.getMissionName());
        detailsFragment.setArguments(fragmentArgs);

        // 确保 Context 是一个 Activity，并且是一个 MainActivity 实例
        if (getContext() instanceof MainActivity) {
            MainActivity activity = (MainActivity) getContext();
            activity.getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.main_frame_layout, detailsFragment)
                    .addToBackStack(null) // 添加到回退栈
                    .commit();
        } else {
            throw new IllegalStateException("The context is not an instance of MainActivity");
        }
        isExpanded = false;
    }

    public void setMissionListViewModel(MissionListViewModel missionListViewModel) {
        this.missionListViewModel = missionListViewModel;
    }
}
